﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace AutonomicComputingLibrary.Helpers
{
    public class XMLManager
    {

        public void CreateHistoryLog(string filename)
        {
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("Monitor"));

            doc.Save(filename);
        }


        public void AddLogEntry(string filename, string _class, string method, string rank)
        {
            try
            {

                XDocument doc = XDocument.Load(filename);



                doc.Element("Monitor").Add(new XElement("Method", new XElement("id", Guid.NewGuid()),
                    new XElement("class", _class), new XElement("method", method), new XElement("rank", rank)));


                doc.Save(filename);
            }
            catch (FileNotFoundException)
            {
                CreateHistoryLog(filename);
                AddLogEntry(filename, _class, method, rank);
            }

            catch
            {
                

            }



    }

        public List<Tuple<Guid, int,string, string>> SelectEntries(string filename)
        {

            var list = new List<Tuple<Guid, int, string, string>>();
            XDocument doc = XDocument.Load(filename);

            foreach (var item in doc.Elements("Monitor").Elements("Method"))
            {
                list.Add(new Tuple<Guid, int, string, string>(new Guid(item.Element("id").Value.ToString()), Convert.ToInt32(item.Element("rank").Value), item.Element("method").Value.ToString(), item.Element("class").Value.ToString()));
            }

            return list;
        }



    }
}
